function getCookie(name) {
    var r = document.cookie.match("\\b" + name + "=([^;]*)\\b");
    return r ? r[1] : undefined;
}


$(function(){

    // 打开登录框
    $('.comment_form_logout').click(function () {
        $('.login_form_con').show();
    })

    // 收藏
    $(".collection").click(function () {
        var params = {
            "news_id":$(this).attr('data-newid'),
            "action":"collected"
        }
        $.ajax({
            url:'/news/news_collected',
            type:'post',
            data:JSON.stringify(params),
            contentType:'application/json',
            headers:{
                'X-CSRFToken':getCookie('csrf_token')
            },
            success:function (resp) {
                if(resp.errno == 0){
                    $(".collection").hide()
                    $(".collected").show()
                }
                else if(resp.errno == '4101'){
                    $(".login_form_con").show()
                }
                else{
                    alert(resp.errmsg)
                }
            }
        })
    })

    // 取消收藏
    $(".collected").click(function () {
        var params = {
            "news_id":$(this).attr('data-newid'),
            "action":"cancel_collected"
        }
        $.ajax({
            url:'/news/news_collected',
            type:'post',
            data:JSON.stringify(params),
            contentType:'application/json',
            headers:{
                'X-CSRFToken':getCookie('csrf_token')
            },
            success:function (resp) {
                if(resp.errno == 0){
                    $(".collection").show()
                    $(".collected").hide()
                }
                else if(resp.errno == '4101'){
                    $(".login_form_con").show()
                }
                else{
                    alert(resp.errmsg)
                }
            }
        })
     
    })

        // 评论提交
    $(".comment_form").submit(function (e) {
        e.preventDefault();
        var params = {
            "news_id":$(this).attr('data-newid'),
            "comment":$('.comment_input').val()
        }
        $.ajax({
            url:'/news/news_comment',
            type:'post',
            data:JSON.stringify(params),
            contentType:'application/json',
            headers:{
                'X-CSRFToken':getCookie('csrf_token')
            },
            success:function(resp){
                if (resp.errno == 0){
                    var comment = resp.data
                    var comment_html = ''
                    comment_html += '<div class="comment_list">'
                    comment_html += '<div class="person_pic fl">'
                    if(comment.user.avatar_url){
                        comment_html += '<img src="'+comment.user.avatar_url+'" alt="用户图标">'
                    }
                    else {
                        comment_html += '<img src="../../static/news/images/worm.jpg" alt="用户图标">'
                    }
                    comment_html += '</div>'
                    comment_html += '<div class="user_name fl">'+comment.user.nick_name+'</div>'
                    comment_html += '<div class="comment_text fl">'
                    comment_html += comment.content
                    comment_html += '</div>'
                    comment_html += '<div class="comment_time fl">'+comment.create_time+'</div>'
                    comment_html += '<a href="javascript:;" class="comment_up has_comment_up fr"  data-comment_id="'+comment.id+'>'+comment.like_count+'</a>'
                    comment_html += '<a href="javascript:;" class="comment_reply fr">回复</a>'
                    comment_html += '<from class="reply_form fl" data-comment_id="'+comment.id+'">'
                    comment_html += '<textarea  class="reply_input"></textarea>'
                    comment_html += '<input type="submit" name="" value="回复" class="reply_sub fr">'
                    comment_html += '<input type="reset" name="" value="取消" class="reply_cancel fr">'
                    comment_html += '</from>'
                    comment_html += '</div>'

                    $('.comment_list_con').prepend(comment_html)
                    $('.comment_sub').blur()
                    $('.comment_input').val('')
                    updateCommentCount()
                }
                else{
                    alert(resp.errmsg)
                }
            }
        })

    })

    $('.comment_list_con').delegate('a,input','click',function(){

        var sHandler = $(this).prop('class');

        if(sHandler.indexOf('comment_reply')>=0)
        {
            $(this).next().toggle();
        }

        if(sHandler.indexOf('reply_cancel')>=0)
        {
            $(this).parent().toggle();
        }

        if(sHandler.indexOf('comment_up')>=0)
        {
            var $this = $(this);
            action = 'add'
            if(sHandler.indexOf('has_comment_up')>=0) {
                // 如果当前该评论已经是点赞状态，再次点击会进行到此代码块内，代表要取消点赞
                action = "remove"
            }
            var params = {
                'comment_id':$this.attr('data-commentid'),
                'action':action
            }
            $.ajax({
                url:'/news/comment_like',
                type:'post',
                data:JSON.stringify(params),
                contentType:'application/json',
                headers:{
                    'X-CSRFToken':getCookie('csrf_token')
                },
                success:function(resp){
                    if(resp.errno == 0){
                        var like_count = $this.attr('data-likecount')
                        if (like_count == undefined){
                            like_count = 0
                        }
                        if(action == 'add'){
                            like_count = parseInt(like_count) + 1
                            $this.addClass('has_comment_up')
                        }
                        else{
                            like_count = parseInt(like_count) - 1
                            $this.removeClass('has_comment_up')
                        }

                        $this.attr('data-likecount',like_count)
                        if (like_count == 0){
                            $this.html("赞")
                        }else {
                            $this.html(like_count)
                        }
                    }
                    else if (resp.errno == "4104"){
                        $('.login_form_con').show();
                    }else {
                        alert(resp.errmsg)
                    }
                }
            })
        }

        if(sHandler.indexOf('reply_sub')>=0)
        {
            var params = {
                "news_id":$(this).parent().attr('data-newid'),
                "comment":$(this).prev().val(),
                "parent_id":$(this).parent().attr('data-commentid')
            }
            $.ajax({
                url:'/news/news_comment',
                type:'post',
                data:JSON.stringify(params),
                contentType:'application/json',
                headers:{
                    'X-CSRFToken':getCookie('csrf_token')
                },
                success:function(resp){
                    if (resp.errno == 0){
                        comment = resp.data
                       var comment_html = ""
                        comment_html += '<div class="comment_list">'
                        comment_html += '<div class="person_pic fl">'
                        if (comment.user.avatar_url) {
                            comment_html += '<img src="' + comment.user.avatar_url + '" alt="用户图标">'
                        }else {
                            comment_html += '<img src="../../static/news/images/person01.png" alt="用户图标">'
                        }
                        comment_html += '</div>'
                        comment_html += '<div class="user_name fl">' + comment.user.nick_name + '</div>'
                        comment_html += '<div class="comment_text fl">'
                        comment_html += comment.content
                        comment_html += '</div>'
                        comment_html += '<div class="reply_text_con fl">'
                        comment_html += '<div class="user_name2">' + comment.parent.user.nick_name + '</div>'
                        comment_html += '<div class="reply_text">'
                        comment_html += comment.parent.content
                        comment_html += '</div>'
                        comment_html += '</div>'
                        comment_html += '<div class="comment_time fl">' + comment.create_time + '</div>'

                        comment_html += '<a href="javascript:;" class="comment_up fr" data-commentid="' + comment.id + '" data-newsid="' + comment.news_id + '">赞</a>'
                        comment_html += '<a href="javascript:;" class="comment_reply fr">回复</a>'
                        comment_html += '<form class="reply_form fl" data-commentid="' + comment.id + '" data-newsid="' +comment.news_id + '">'
                        comment_html += '<textarea class="reply_input"></textarea>'
                        comment_html += '<input type="button" value="回复" class="reply_sub fr">'
                        comment_html += '<input type="reset" name="" value="取消" class="reply_cancel fr">'
                        comment_html += '</form>'

                        comment_html += '</div>'
                        $(".comment_list_con").prepend(comment_html)
                        // 请空输入框
                        $this.prev().val('')
                        // 关闭
                        $this.parent().hide()
                        updateCommentCount()
                    }
                    else{
                        alert(resp.errmsg)
                    }
                }
            })
        }
    })

        // 关注当前新闻作者
    $(".focus").click(function () {
        var user_id = $(this).attr('data-userid')
        var params = {
            "user_id":user_id,
            "action":"follow"
        }
        $.ajax({
            url:"/news/user_followed",
            type:'post',
            data:JSON.stringify(params),
            contentType:"application/json",
            headers:{
                "X-CSRFToken":getCookie('csrf_token')
            },
            success:function(resp){
                if (resp.errno == 0){
                    var count = parseInt($('.follows b').html())
                    count++;
                    $('.follows b').html(count+"")
                    $('.focus').hide()
                    $('.focused').show()
                }
                else if (resp.errno == 4104){
                    $('.login_form_con').show()
                }
                else{
                    alert(resp.errmsg)
                }
            }
        })
    })

    // 取消关注当前新闻作者
    $(".focused").click(function () {
        var user_id = $(this).attr('data-userid')
        var params = {
            "user_id":user_id,
            "action":"unfollow"
        }
        $.ajax({
            url:"/news/user_followed",
            type:'post',
            data:JSON.stringify(params),
            contentType:"application/json",
            headers:{
                "X-CSRFToken":getCookie('csrf_token')
            },
            success:function(resp){
                if (resp.errno == 0){
                    var count = parseInt($('.follows b').html())
                    count--;
                    $('.follows b').html(count+"")
                    $('.focus').show()
                    $('.focused').hide()
                }
                else if (resp.errno == 4104){
                    $('.login_form_con').show()
                }
                else{
                    alert(resp.errmsg)
                }
            }
        })
    })
})

function updateCommentCount(){
    var count = $('.comment_list').length
    $('.comment_count').html(count+'条评论')
}